//
//  NewsTableViewController.m
//  555彩票
//
//  Created by zhoubo on 2017/7/4.
//  Copyright © 2017年 zhoubo. All rights reserved.
//

#import "NewsTableViewController.h"
#import "News.h"
#import "NewsCell.h"
#import "NewsTableViewController.h"
#import "NewsDetailViewController.h"
#import "SVProgressHUD.h"
#import "ZBPullDownRefreshView.h"
#import "Head.h"

@interface NewsTableViewController ()



@end

@implementation NewsTableViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.refreshView.status = Refreshing;
    NSLog(@"news table will appear");

}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    NSLog(@"news table viewdidload");
    
    

    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    

    [self.tableView addSubview:self.refreshView];
    
    

    

//    self.refreshView.backgroundColor = [UIColor purpleColor];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.automaticallyAdjustsScrollViewInsets = false;
    
    //®®®设置边距为navigationbar何channelview的高度和 否则tableview无法正常显示最后一条数据
    // 或者在自定义cell里设置newsCon的frame等于cell的bounds
//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 108, 0);
    
//    [self refresh];

}

-(void)setIndex:(NSInteger)index
{
    _index = index;

}



//-(void)viewWillAppear:(BOOL)animated
//{
//    if (self.news.count == 0) {
//        [self refresh];
//    }
//}

-(void)setNews:(NSArray *)news
{
    _news = news;
    [self.tableView reloadData];
}


-(void)refresh
{

        [News loadNewsWithName:@"news" success:^(NSArray *news) {
            
            //如果数据成功 结束刷新
            [self.refreshView endrefresh];
            
            self.news = news;
            //        [self.tableView reloadData];

            [self randomNews];

            
        } faild:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络不给力"];
            self.refreshView.status = Normal;
            
            // 让父控制器将自己从缓存池中移除
            if (self.removeCacheBlock) {
                self.removeCacheBlock();
            }
            
            NSLog(@"%@",error);
        }];
    

}

-(void)randomNews
{
    if (self.index != 0) {
        NSArray *array = self.news;
        NSMutableSet *randomSet = [[NSMutableSet alloc] init];
        
        while ([randomSet count] < self.news.count) {
            int r = arc4random() % [array count];
            [randomSet addObject:[array objectAtIndex:r]];
        }
        
        self.news = [randomSet allObjects];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    tableView.contentSize = CGSizeMake(0, self.news.count*tableView.rowHeight);
    return self.news.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"news"    forIndexPath:indexPath];
    
    // Configure the cell...

    cell.news = self.news[indexPath.row];

    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    News* news = self.news[indexPath.row];
    NewsDetailViewController* detailcon = [[NewsDetailViewController alloc]init];
    detailcon.news = news;
    
//    NSLog(@"%@",self.view.superview);
    [self.navigationController pushViewController:detailcon animated:YES];
}







-(ZBPullDownRefreshView *)refreshView
{
    if (_refreshView == nil) {
        _refreshView = [[ZBPullDownRefreshView alloc]init];
        
        __weak typeof(self) weakself = self;
        __weak typeof (_refreshView) weakRefreshview = _refreshView;        

        _refreshView.refreshBlock = ^(){
            
            if (weakself.news.count == 0) {
                [weakself refresh];
            }
            else
            {

                dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC);

                dispatch_after(time, dispatch_get_main_queue(), ^{
                    
                    [weakRefreshview endrefresh];
                });
                
            }
        };


        

    }
    return _refreshView;
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
